import mido
from mido import MidiFile


mid = MidiFile("安静.弹唱版.mid")
# mid = MidiFile("晴天（钢琴巨长版）.mid")

tempo = mido.bpm2tempo(120)
print(tempo)
play_list = []
for i, track in enumerate(mid.tracks):
    print('Track {}: {}'.format(i, track.name))
    play_list.append([])

    passed_time = 0
    cur_tempo = mido.bpm2tempo(76)
    cur_speed = 0
    for msg in track:
        # print(msg.type, msg)
        ab_time = mido.tick2second(msg.time, mid.ticks_per_beat, cur_tempo)

        real_time = ab_time + passed_time
        passed_time += ab_time
        if msg.type == "note_on":
            note = msg.note
            if msg.velocity == 0:
                play_list[i].append([note, 0, real_time, 100])
            else:
                play_list[i].append([note, 1, real_time, msg.velocity if msg.velocity < 100 else 100])
        elif msg.type == "note_off":
            note = msg.note
            play_list[i].append([note, 0, real_time, 0])
            # passed_time -= 0.03
        # elif msg.type == "set_tempo":
        #     cur_tempo = msg.tempo





import sys
sys.path.append('../../')
sys.path.append('../../../../')
if __name__ == "__main__":
    import piano.music_translate2 as music_translate
    music_parse = music_translate.music_trans([], beat = 80)
    play_list[0].extend(play_list[1])
    music_parse.play_list = play_list[2]
    music_parse.play_list_sort()
    music_parse.play_music(mode = "midi")